import { login as loginService } from '@/services/auth';
import { message } from 'antd';
import { useState } from 'react';
import { history, useModel } from 'umi';

export default () => {
  const [loading, setloading] = useState(false);
  const { setInitialState } = useModel('@@initialState');

  const login = async (values: API.LoginParams) => {
    setloading(true);
    const { code, data, msg } = await loginService({ ...values });
    setloading(false);
    if (code === 0) {
      const { user, accessExpiration, refreshExpiration, ...token } = data;
      setInitialState((s) => ({ ...s, currentUser: user }));

      localStorage.setItem('user', JSON.stringify(user));
      localStorage.setItem(
        'token',
        JSON.stringify({
          ...token,
          accessExpiration: accessExpiration * 1000,
          refreshExpiration: refreshExpiration * 1000,
          creatTime: new Date().getTime(),
        }),
      );

      if (!history) return;
      const { query } = history.location;
      const { redirect } = query as { redirect: string };
      history.push(redirect || '/');
    } else {
      message.error(msg);
    }
  };
  return { login, loading };
};
